package com.skytech.component.monitor.util;

import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.data.MonitorDataDAO;
import com.skytech.component.monitor.data.MonitorDataTag;
import com.skytech.component.monitor.data.MonitorDataTagDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;


@Service
public class SaveDataUtil {


    @Autowired
    private MonitorDataDAO monitorDataDAO;
    @Autowired
    private MonitorDataTagDAO monitorDataTagDAO;




    public void saveTag( List<MonitorData> monitorDataList,String province){
        for (MonitorData monitorData : monitorDataList) {
            String UniqueKey = monitorData.getCompanyName() + "--" + monitorData.getMonitorPoint() + "--" + monitorData.getMonitorInfo();
            MonitorDataTag monitorDataTag = new MonitorDataTag();
            monitorDataTag.setProvince(province);
            monitorDataTag.setUniqueKey(UniqueKey);
            List<MonitorDataTag> History = monitorDataTagDAO.findAll(Example.of(monitorDataTag));
            saveData(monitorData, History, UniqueKey,province);
        }
    }


    private  void saveData(MonitorData monitorData, List<MonitorDataTag> monitorDataTagList, String uniqueKey,String province) {
        if (monitorDataTagList.isEmpty()) {
            monitorDataDAO.save(monitorData);
            MonitorDataTag monitorDataTag = new MonitorDataTag();
            monitorDataTag.setId(UUID.randomUUID().toString());
            monitorDataTag.setProvince(province);
            monitorDataTag.setUniqueKey(uniqueKey);
            monitorDataTag.setLabel(monitorData.getMonitorTime());
            monitorDataTagDAO.save(monitorDataTag);
        } else {
            if (monitorDataTagList.get(0).getLabel().equals(monitorData.getMonitorTime())) {

            } else if (monitorDataTagList.get(0).getLabel().compareTo(monitorData.getMonitorTime()) < 0) {
                monitorDataDAO.save(monitorData);

                MonitorDataTag monitorDataTagUpdate = monitorDataTagList.get(0);
                monitorDataTagUpdate.setLabel(monitorData.getMonitorTime());
                monitorDataTagDAO.save(monitorDataTagUpdate);

            } else if(monitorDataDAO.findByCompanyNameAndMonitorInfoAndMonitorPointAndMonitorTimeAndMonitorType(monitorData.getCompanyName(),monitorData.getMonitorInfo(),monitorData.getMonitorPoint(),monitorData.getMonitorTime(),monitorData.getMonitorType()).isEmpty()) {
                monitorDataDAO.save(monitorData);
            }

        }

    }
}
